package com.cj.apiserver.client;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.cj.apiserver.model.User;
import com.cj.apiserver.utils.StringUtils;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author cc
 * @date 2025-03-23 14:49
 **/
@Component
public class ApiClient {


    private String GATEWAY_HOST = "http://localhost:8080";
    private String accessKey="waterkid";
    private String secretKey="abc";


    public String getUsernameByPost(User user){
        String json = JSONUtil.toJsonStr(user);
        HttpResponse httpResponse = HttpRequest.post(GATEWAY_HOST+"/user")
                .addHeaders(getHeaderMap(json))
                .body(json)
                .execute();

        System.out.println(httpResponse.getStatus());
        String result = httpResponse.body();
        System.out.println("result = " + result);
        return  result;
    }


    private Map<String,String> getHeaderMap(String body){
        Map<String, String> map = new HashMap<>();
        map.put("accessKey",accessKey);
        map.put("nonce", RandomUtil.randomNumbers(4));
        map.put("timestamp",System.currentTimeMillis()+"");
        map.put("body",body);
        map.put("sign", StringUtils.genSign(body,secretKey));

        return map;
    }
}
